package pers.tz.题目;

import pers.tz.common.ArrayUtils;

/**
 * @author irony
 * @date 2024-03-15
 */
public class 数组中有多少绝对值不同的元素 {
    public static void main(String[] args) {
        int[] ints = ArrayUtils.generateRandomArray(5, true, -10, 10);
        ArrayUtils.printArray(ints);

        System.out.println(countUniqueAbsoluteValues(ints));
    }

    // 左右双指针
    private static int countUniqueAbsoluteValues(int[] ints) {
        if (ints == null || ints.length == 0) {
            return 0;
        }

        int start = 0;
        int last = ints.length - 1;
        int ans = 0;
        int prev = -1;

        while (start <= last) {
            int abs1 = Math.abs(ints[start]);
            int abs2 = Math.abs(ints[last]);

            if (abs1 == abs2) {
                // 跳过连续的情况
                if (abs1 != prev) {
                    ans++;
                    prev = abs1;
                }

                start++;
                last--;
            }
            else if (abs1 > abs2) {
                if (abs1 != prev) {
                    ans++;
                    prev = abs1;
                }
                start++;
            }
            else { // abs1 < abs2
                if (abs2 != prev) {
                    ans++;
                    prev = abs2;
                }
                last--;
            }
        }

        return ans;
    }

}
